package org.pearl.thread.demo.test002;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by TD on 2021/4/16
 * 原子性
 */
public class AtomicityTest001 {
    private static int num = 0;

    private static Object MUTEX = new Object();

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                synchronized (MUTEX) {
                    num++;
                }
            }
        };
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(task);
            thread.start();
            list.add(thread);
        }
        // join操作，保证以上任务线程执行完毕，再输出num
        for (Thread thread : list) {
            thread.join();
        }
        System.out.println(num);
    }
}
